/**
 * Exercise 3.33
 * Develop a version of Program 3.9 that uses an array of indices to implement the linked list (see Figure 3.6).
 * -------------------------------------------------------------------------------------------------------------
 * 思路：
 * 使用两个数组来实现链表
 * - item数组存储数据
 * - next数组存储每个数据指向的下一个数据的索引，即链接
 */

#include <stdlib.h>
#include <stdio.h>

typedef int Item;

int main(int argc, char **argv) {
    if (argc != 3) {
        printf("Usage:%s N M\n", argv[0]);
        return 1;
    }
    int N = atoi(argv[1]);
    int M = atoi(argv[2]);
    int i;

    Item *item = malloc(N*sizeof(Item));
    Item *next = malloc(N*sizeof(Item));

    for (i = 0; i < N; i++) {
        item[i] = i+1;
        next[i] = (i+1)%N;
    }

    int x = N-1;
    while (next[x] != x) {
        for (i = 1; i < M; i++) {
            x = next[x];
        }
        int t = next[x];
        next[x] = next[t];
        printf("%d ", item[t]);
        N--;
    }
    printf("\n");
    printf("%d\n", item[x]);


    return 0;
}
